from django.shortcuts import render, redirect, reverse, HttpResponse
from chart_web.form import account, kaidan
from django.http import JsonResponse
from chart_web import models
from uuid import uuid4
from utils import Md5
import datetime
from utils.pagination import Pagination


def kaidan_restaurant(request):
    '''怪谈文章渲染'''
    # 如果是get请求，查询当前所有的文章，进行渲染(一页12个)
    if request.method == 'GET':
        # 获取所有的文章
        queryset = models.KaidanRestaurant.objects.filter(is_delete=False)
        page_object = Pagination(
            current_page=request.GET.get('page'),
            all_count=queryset.count(),
            base_url=request.path_info,
            query_params=request.GET,
            per_page=10,
        )
        kaidan_restaurant_article = queryset[page_object.start:page_object.end]
        page_html = page_object.page_html()
    return render(request, 'kaidan_restaurant.html', locals())


def article_add(request, username):
    '''怪谈文章添加 前端页面待修改'''
    # 如果是get请求，渲染添加页面
    if request.method == 'GET':
        form = kaidan.kaidan_article(request)
        return render(request, 'md.html', locals())
    # form 校验
    form = kaidan.kaidan_article(request, data=request.POST)
    if form.is_valid():
        # 通过保存
        form.instance.userinfo = request.chart_web.user
        instance = form.save()
        return redirect('kaidan_restaurant')
    # 不通过返回错误信息
    return render(request, 'md.html', locals())


def kaidan_article(request, pk):
    '''文章详细页面/评论渲染 前端页面待修改'''
    # 根据传过来的pk查询当前文章，进行渲染
    if request.method == 'GET':
        # 评论渲染
        comment_obj = models.UpDownComment.objects.filter(kaidan_restaurant_id=pk, is_delete=False,
                                                          type_comment=3, type_up_down=3).all().order_by('-Step_up')
        # 文章详细渲染
        article_obj = models.KaidanRestaurant.objects.filter(pk=pk, is_delete=False).first()
        return render(request, 'kaidan_article.html', locals())


def Step_up(request, pk):
    '''怪谈文章点赞'''
    dic = {
        'status': 1,
        'msg': ''
    }
    _request = request.chart_web.user
    up_down_object = models.UpDownComment.objects.filter(userinfo=_request, kaidan_restaurant_id=pk)
    # 查询当前用户,有没有在当前文章上有记录
    exist = up_down_object.exists()
    if exist:
        # 存在记录
        # 在已经点赞的情况下，如果想在点赞，抛异常
        up_down_obj = up_down_object.first()
        # 通过点赞确认字段来判断
        if up_down_obj.Step_up_true:
            # rise 异常
            dic['status'] = 0
            dic['msg'] = '不要贪杯哦！'
            return JsonResponse(dic)
        else:
            # 如果点过踩了，想点赞
            # 通过Step_down来进行判断
            # 把确认点踩字段更新false
            up_down_obj.Step_down_true = False
            # 把点赞字段跟新为True
            up_down_obj.Step_up_true = True
            up_down_obj.save()
            # 怪谈文章进行相应的加减
            kaidan_restaurant_objects = models.KaidanRestaurant.objects.filter(id=pk).first()
            kaidan_restaurant_objects.Step_down -= 1
            kaidan_restaurant_objects.Step_up += 1
            kaidan_restaurant_objects.save()
            dic['status'] = 2
            return JsonResponse(dic)
    else:
        # 第一次赞
        # 创建怪谈文章点赞记录
        up_down_obj = models.UpDownComment.objects.create(
            type_comment=1,
            type_up_down=1,
            kaidan_restaurant_id=pk,
            userinfo=_request,
        )
        # 进行相应的加减
        # 点赞确定字段更新True
        up_down_obj.Step_up_true = True
        up_down_obj.save()
        # 怪谈文章进行相应的加减
        kaidan_restaurant_objects = models.KaidanRestaurant.objects.filter(id=pk).first()
        kaidan_restaurant_objects.Step_up += 1
        kaidan_restaurant_objects.save()
        return JsonResponse(dic)


def Step_down(request, pk):
    '''怪谈文章点踩'''
    dic = {
        # status：1 status:2
        'status': 1,
        'msg': ''
    }
    _request = request.chart_web.user
    up_down_object = models.UpDownComment.objects.filter(userinfo=_request, kaidan_restaurant_id=pk)
    # 查询当前用户,有没有在当前文章上有记录
    exist = up_down_object.exists()
    if exist:
        # 存在记录
        # 在已经点踩的情况下，如果想在点踩，抛异常
        up_down_obj = up_down_object.first()
        # 通过点赞确认字段来判断
        if up_down_obj.Step_down_true:
            # rise 异常
            dic['status'] = 0
            dic['msg'] = '/(ㄒoㄒ)/~~给留条后路把'
            return JsonResponse(dic)
        else:
            # 如果点过赞了，想点踩
            # 把确认点踩字段更新false
            up_down_obj.Step_down_true = True
            # 把点赞字段跟新为False
            up_down_obj.Step_up_true = False
            up_down_obj.save()
            # 怪谈文章进行相应的加减
            kaidan_restaurant_objects = models.KaidanRestaurant.objects.filter(id=pk).first()
            kaidan_restaurant_objects.Step_down += 1
            kaidan_restaurant_objects.Step_up -= 1
            kaidan_restaurant_objects.save()
            dic['status'] = 2
            return JsonResponse(dic)
    else:
        # 第一次踩
        # 创建怪谈文章  点赞记录
        up_down_obj = models.UpDownComment.objects.create(
            type_comment=1,
            type_up_down=1,
            kaidan_restaurant_id=pk,
            userinfo=_request,
        )
        # 进行相应的加减
        # 点赞确定字段更新True
        up_down_obj.Step_down_true = True
        up_down_obj.save()
        # 怪谈文章进行相应的加减
        kaidan_restaurant_objects = models.KaidanRestaurant.objects.filter(id=pk).first()
        kaidan_restaurant_objects.Step_down += 1
        kaidan_restaurant_objects.save()
        return JsonResponse(dic)


def kaidan_comment(request, pk):
    """怪谈文章评论"""
    dic = {
        'status': 1,
        'msg': ''
    }
    if request.method == 'GET':
        return render(request, 'kaidan_article.html')
    form = kaidan.comment_form(data=request.POST)
    if form.is_valid():
        # 保存数据
        parent = request.POST.get('parent')
        # 创建怪谈评论/点赞/点踩记录
        models.UpDownComment.objects.create(
            type_comment=3,
            type_up_down=3,
            comment=form.cleaned_data.get('comment'),
            kaidan_restaurant_id=pk,
            parent_id=parent,
            userinfo=request.chart_web.user
        )
        return JsonResponse(dic)
    dic['status'] = 0
    dic['msg'] = form.errors
    return JsonResponse(dic)


def kaidan_comment_up(request, comment_id):
    '''怪评论点赞'''
    comment_up_obj = models.UpDownComment.objects.filter(id=comment_id, is_delete=False,
                                                         type_up_down=3, type_comment=3).first()
    comment_up_obj.Step_up += 1
    comment_up_obj.save()
    return redirect('kaidan_restaurant')


def kaidan_comment_down(request, comment_id):
    '''怪评论点踩'''
    comment_down_obj = models.UpDownComment.objects.filter(id=comment_id, is_delete=False,
                                                           type_comment=3).first()
    comment_down_obj.Step_down += 1
    comment_down_obj.save()
    return redirect('kaidan_restaurant')
